package com.theanh.RssActivity.updater;

import java.util.ArrayList;
import java.util.List;

import android.database.SQLException;
import android.graphics.Bitmap;
import android.util.Log;

import com.theanh.RssActivity.db.DbAdapter;
import com.theanh.RssActivity.entity.Channel;
import com.theanh.RssActivity.entity.Item;
import com.theanh.RssActivity.ui.model.ItemModel;
import com.theanh.RssActivity.util.DbUtils;
import com.theanh.RssActivity.util.FileUtils;
import com.theanh.RssActivity.util.RssUtils;
import com.theanh.RssActivity.util.Utils;

public class ImageItemUpdater extends Thread {

	private static final String TAG = "ImageItemUpdater";
	private boolean running = false;
	private List<Item> items;
	private List<ItemModel> models;

	public List<ItemModel> getModels() {
		return models;
	}

	public void setModels(List<ItemModel> models) {
		this.models = models;
	}

	public List<Item> getItems() {
		return items;
	}

	public void setItems(List<Item> items) {
		this.items = items;
	}

	public ImageItemUpdater() {
		super();
		items = new ArrayList<Item>();
	}

	public void addItemModel(Item model) {
		items.add(model);
	}

	public List<Item> getListItemModel() {
		return items;
	}

	public void setListItemModel(List<Item> listItemModel) {
		this.items = listItemModel;
	}

	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

	@Override
	public void run() {
		Log.w(TAG, "Running...");
		if (items == null || items.size() == 0)
			return;

		for (Item item : items) {
			if (item == null || item == null
					|| item.getImage() != null)
				continue;
			Log.i(TAG, "IMAGE_URL=" + item.getImageUrl());
//			String imageUrl = Utils.paresImageUrlFromXml(item
//					.getDescription());
			
			if (item.getImage() == null){
				// Load bitmap from internet
				Bitmap bitmap = Utils.loadImage(item.getImageUrl());
				item.setImage(bitmap);
				if(models != null)
					continue;
				for(ItemModel model : models){
					if (model == null || model.item == null)
						continue;
					if (model.item.equals(item))
						model.displayImageDescription();
				}
	
				FileUtils.writeImage(bitmap, item.getID());
			}else{
				Log.i(TAG,"item.getImage not null");
			}
//			model.displayImageDescription();
		}
	}
}
